package com.ganyu.filter;

import com.alibaba.fastjson.JSON;
import com.ganyu.component.RedisCache;
import com.ganyu.domain.LoginUser;
import com.ganyu.domain.ResponseResult;
import com.ganyu.utils.JwtUtil;
import com.ganyu.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.ganyu.enums.AppHttpCodeEnum.NEED_LOGIN;

/**
 * DATA: 2022/9/15
 * Author: 晨夕
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //1. 在请求头中获取token
        String token = httpServletRequest.getHeader("token");
        //1.2 未获取到token，说明该操作不需用户信息，直接放行
        if(!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //2.解析token获取userId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //2.1 token和后台生成的token不一致会报异常，提醒用户重新登录，token超时也报异常
            //响应给前端
            ResponseResult responseResult = ResponseResult.errorResult(NEED_LOGIN);
            WebUtils.renderString(httpServletResponse, JSON.toJSONString(responseResult));
            return;

        }
        //3.根据userId从redis中获取用户信息
        String id = claims.getSubject();
        LoginUser loginUser = redisCache.getCacheObject("userId:" + id);
        //3.1 判断是否能获取到loginUser
        if(Objects.isNull(loginUser)){
            //获取不到
            ResponseResult responseResult = ResponseResult.errorResult(NEED_LOGIN);
            WebUtils.renderString(httpServletResponse, JSON.toJSONString(responseResult));
            return;
        }
        //4.将获取的用户信息存入SecurityContextHolder中
        // TODO 授权
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //5. 放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
